#
# @lc app=leetcode.cn id=337 lang=python
#
# [337] 打家劫舍 III
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def rob(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        t, nott = self.loop(root)
        return max(t, nott)
        
    def loop(self, node):
        if not node:
            return 0, 0

        t_left, not_left = self.loop(node.left)
        t_right, not_right = self.loop(node.right)

        return not_left + not_right+node.val, max(t_left, not_left) + max(t_right, not_right)
        
# @lc code=end

